<template>
  <div>
    <!-- 当点击 取消按钮 时，关闭弹窗 -->
    <el-drawer
      :title="title"
      :visible.sync="visible"
      size="60%"
      :append-to-body="true"
      @close="clearDialog()"
      v-loading="loding"
      :destroy-on-close="true"
    >
      <div style="padding: 20px">
        <ele-form
          v-model="createData"
          v-bind="formConfig"
          ref="formDialog"
          v-loading="loading"
        ></ele-form>
        <ele-table-editor
          ref="table-editor"
          :isShowAdd="false"
          :isShowDelete="false"
          :columns="columns"
          v-model="capacityTableForm"
        >
          <!-- 容量 -->
          <template v-slot:count="{ data }">{{ data.count }}</template>
          <!-- 数值 -->
          <template v-slot:amount="{ data }">{{ data.amount }}</template>
          <!-- 已打数值 -->
          <template v-slot:hasPrintNum="{ data }">{{ data.hasPrintNum }}</template>
        </ele-table-editor>
        <barcode-print
          :barcodeInfo="barcodeInfoImage"
          ref="print"
          :key="time"
          :isPrint="false"
          v-if="Object.keys(barcodeInfoImage).length > 0"
        ></barcode-print>

        <div slot="footer" class="dialog-footer">
          <el-button @click="clearDialog()">{{
            $t("common.cancel")
          }}</el-button>
          <el-button type="danger" @click="clearCode">{{ $i18n.t("mesCapacityCodePrinting.clearCapacityCode") }}</el-button>
          <el-button
            v-if="dialogfrom.isCreateBarcode == 1 && printCodeOk"
            type="primary"
            @click="handleShow"
            >{{ $t("printBoxCode.previewAndPrint") }}</el-button
          >
        </div>
      </div>
    </el-drawer>
    <templateSelect
      ref="templateSelect"
      v-model="createData.barcodePrintTempCode"
      :searchData="{
        goodsCode: createData.goodsCode,
        businessTypeCode: businessTypeMap[createData.printSort],
      }"
      @select="getTempCode"
    ></templateSelect>
  </div>
</template>

<script>
import {
  genCodeBatch, //批量生码
  // clearBoxcode,
  // selectListByConfigurationCode,
  checkCapacityCode, //校验是否已经生成对应类型容量码
  templateType, //获取生码分类
  getProdByOrder, //根据订单获取型号
  selectCommonProduceRelByProduce, //根据型号、分类获取生码规则接口
  getCapacityCodeList, //获取容量/数量列表接口,
  detailbyName,
  splitPrintList, //获取本次要打印的条码信息
} from "@/api/print/mesCapacityCode";
import templateSelect from "@/components/templateSelect/index.vue";

import qs from "qs";
import BarcodePrint from "@/components/barcodePrint/barcodePrint";
import EleTableEditor from "ele-table-editor";
import sys from "@/config";
let arrBarcodePrintingList2 = [];

export default {
  name: "barcodePrintingAddModel",
  watch: {
    visible(val, oldVal) {
      if (!val) {
        this.$refs.formDialog.resetForm();
        this.barcodeInfo = {};
      }
    },
    "createData.barcodePrintTemp": {
      handler(newVal, oldVal) {
        this.getTemplateName(newVal);
      },
      deep: true,
    },
  },
  props: {
    title: {
      type: String,
      default: "",
    },
  },
  components: { BarcodePrint, EleTableEditor, templateSelect },
  data() {
    let _this = this;
    return {
      businessTypeMap: {
        box_code: "PRINT_MES_PC_PACKAGEING_BOX_CODE",
        pack_code: "PRINT_MES_PC_INNER_PACKING_BOX_CODE",
        tray_code: "PRINT_MES_PC_PALLET_CODE",
      },
      loding: false,
      time: 0,
      capacityTableForm: [],
      // 容量表格
      columns: [
        {
          // el-table-column 的属性
          type: "index",
        },
        {
          // el-table-column 的属性
          prop: "count",
          label: $i18n.t("mesCapacityCodePrinting.volume"),
          // 支持 显示隐藏
          vif: true,
        },
        {
          prop: "amount",
          label: $i18n.t("mesCapacityCodePrinting.unprintedQuantity"),
        },
        {
          prop: "hasPrintNum",
          label: $i18n.t("mesCapacityCodePrinting.quantityPrinted"),
        },
      ],
      formConfig: {
        span: 24,
        isShowBackBtn: false,
        isShowSubmitBtn: false,
        labelPosition: "right",
        formDesc: {
          orderCode: {  // 生产工单编码
            type: "input",
            label: $i18n.t("mesCapacityCodePrinting.orderCode"),
            layout: 12,
            disabled: true,
          },
          printSort: {  // 生码类型
            type: "select",
            label: $i18n.t("mesCapacityCodePrinting.printSort"),
            layout: 12,
            prop: {
              value: "value",
              text: "description",
            },
            options: async (data) => {
              const params = {};
              const list = await templateType(params);
              return list.data.result;
            },
            on: {
              change(val) {
                _this.createData.printSort = val;
                (_this.formConfig.formDesc.goodsCode.options = async (data) => {
                  const params = {
                    orderCode: data.orderCode,
                  };
                  const list = await getProdByOrder(params);
                  _this.goodsCodeList = list.data.result;
                  return list.data.result;
                }),
                  _this.changeCode();
              },
            },
            required: true,
            disabled: false,
          },
          goodsCode: {  // 物料
            type: "select",
            label: $i18n.t("mesCapacityCodePrinting.goodsCode"),
            layout: 12,
            prop: {
              value: "prodCode",
              text: "prodName",
            },
            options: async (data) => {
              const params = {
                orderCode: data.orderCode,
              };
              const list = await getProdByOrder(params);
              _this.goodsCodeList = list.data.result;
              return list.data.result;
            },
            slots: {
              default(h, options) {
                let data = _this.goodsCodeList;
                if (data && data.length > 0) {
                  return data.map((option) =>
                    h("el-option", { attrs: { value: option.prodCode } }, [
                      h("span", { style: { float: "left" } }, option.prodName),
                      h(
                        "span",
                        {
                          style: {
                            float: "right",
                            color: "#8492a6",
                            fontSize: "13px",
                          },
                        },
                        option.prodCode
                      ),
                    ])
                  );
                } else {
                  return [];
                }
              },
            },
            on: {
              change(val) {
                _this.createData.goodsCode = val;
                let goodsCodeList = _this.goodsCodeList;
                let goodsCode = goodsCodeList.find((item) => {
                  return item.prodCode == val;
                });
                if (goodsCode) {
                  _this.createData.productType = goodsCode.productType;
                }
                _this.changeCode();
              },
            },
            required: true,
            disabled: false,
          },
          barcodePrintTemp: {
            type: "input",
            label: $i18n.t("mesCapacityCodePrinting.labelTemplate"),
            required: true,
            layout: 12,
            disabled: (data) => {
              return data.selTemplateDisabled;
            },
            attrs: {
              readonly: true,
            },
            slots: {
              append(h) {
                return (
                  <el-button
                    icon="el-icon-search"
                    disabled={_this.createData.selTemplateDisabled}
                    onClick={() => {
                      _this.$refs.templateSelect.show();
                    }}
                  ></el-button>
                );
              },
            },
          },
        },
      },
      createData: {
        orderCode: null,
        goodsCode: null,
        printSort: null,
        barcodePrintTemp: null,
        productType: null,
        selTemplateDisabled: false,
      },
      goodsCodeList: [],
      detailList: [],
      barcodeInfo: {},
      barcodeInfoImage: {},
      dialogfrom: {},
      visible: false,
      loading: false,
      printCodeOk: false,
      form: {
        amount: 0,
      },
      rules: {
        amount: [
          {
            required: true,
            message: $i18n.t("mesCapacityCodePrinting.printingQuantity"),
            trigger: "blur",
          },
        ],
      },
      maxnum: 9999,
      list: [],
    };
  },

  methods: {
    clearCode() {
      this.$emit("clearCode");
    },
    getTempCode(data) {
      this.$set(this.createData, "barcodePrintTemp", data.name);
      this.$set(this.createData, "barcodePrintTempCode", data.code);
    },
    //初始化
    init(params) {
      this.dialogfrom = params;
      this.barcodeInfo = params;
      this.createData.orderCode = params.orderCode;
      this.visible = true;
    },

    async getBarcodePrintTempList() {
      const res = await getBarcodePrintTempList();
      arrBarcodePrintingList2 = res.data.result;
    },
    /**
     * @author bing
     * @since 2022-11-17 11:13:11
     * 清楚箱码
     */
    async clearBoxcode() {
      try {
        let { value } = await this.$prompt(
          $i18n.t("mesCapacityCodePrinting.inputClearUniqueCodeReason2"),
          $i18n.t("common.tip"),
          {
            confirmButtonText: $i18n.t("common.ok"),
            cancelButtonText: $i18n.t("common.cancel"),
            inputValidator: (value) => {
              if (!value) {
                return $i18n.t("mesCapacityCodePrinting.inputClearUniqueCodeReason2");
              }
            },
          }
        );
        if (!value) {
          this.$message.warning(
            $i18n.t("mesCapacityCodePrinting.inputClearUniqueCodeReason2")
          );
          return;
        }
        this.loding = true;
        let res = await clearBoxcode({
          clearReason: value,
          orderCode: this.dialogfrom.orderCode,
        });

        let deflt = this.dialogfrom.count;
        this.dialogfrom.count = 999;
        this.$nextTick(() => {
          this.dialogfrom.count = deflt;

          this.getBoxCount();
          this.$set(this.dialogfrom, "isCreateBarcode", 0);
        });
      } finally {
        this.loding = false;
      }
    },
    //类型型号选择处理
    changeCode() {
      const createData = this.createData;
      // 当分类和型号都存在时获取效验容量码是否生成
      if (createData.printSort && createData.goodsCode) {
        let params = {
          goodsCode: createData.goodsCode,
          templateType: createData.printSort,
          type: "template",
        };

        selectCommonProduceRelByProduce(params).then(async (res) => {
          this.formConfig.formDesc.barcodePrintTemp.options = res.data.result;
          const list = await this.getRuleAndTemplate();

          if (!list || this.list.length == 0) {
            let tableData = list;
            let printCodeOk = false;
            tableData.forEach((item) => {
              item.amount =
                parseInt(item.sumCodeNum) - parseInt(item.hasPrintNum);
              item.unPrintNum =
                parseInt(item.sumCodeNum) - parseInt(item.hasPrintNum);
              if (item.amount > 0) {
                printCodeOk = true;
              }
            });
            this.printCodeOk = printCodeOk;
            this.capacityTableForm = tableData;
            this.dialogfrom.isCreateBarcode = 1;
          } else {
            this.capacityTableForm = [];
            this.$confirm(
              $i18n.t("mesCapacityCodePrinting.isCreateBarcode"),
              $i18n.t("common.tip"),
              {
                confirmButtonText: $i18n.t("common.ok"),
                cancelButtonText: $i18n.t("common.cancel"),
                type: "warning",
              }
            ).then(() => {
              this.$parent.showCreateNext({
                orderCode: createData.orderCode,
                prodCode: createData.goodsCode,
                productType: createData.productType,
                capacityType: createData.printSort,
              });
              this.clearDialog();
            });
          }
        });
      }
    },
    // 查询一下是否已经生过码，如果生过码就用以前的编码规则和模板
    async getRuleAndTemplate() {
      let check = {
        orderCode: this.createData.orderCode,
        prodCode: this.createData.goodsCode,
        productType: this.createData.productType,
        capacityType: this.createData.printSort,
      };
      const codeListRes = await getCapacityCodeList(check);
      const { result } = codeListRes.data;
      this.createData.selTemplateDisabled = "";
      this.createData.selTemplateDisabled = !!result.barcodePrintTempCode;
      this.formConfig.formDesc.barcodePrintTemp.disabled =
        !!result.barcodePrintTempCode;

      this.getTempCode({
        name: result.barcodePrintTemp || "",
        code: result.barcodePrintTempCode || "",
      });

      return result.barCodeResult;
    },
    //获取模板详情
    getTemplateName(templateName) {
      if (templateName) {
        const params = {
          templateName,
        };
        detailbyName(params).then((res) => {
          if (res.data.success) {
            if (res.data.result.length > 0) {
              this.time = new Date().getTime();
              this.barcodeInfoImage = {
                ...this.barcodeInfo,
                ...res.data.result[0],
              };
            }
          }
        });
      } else {
        this.barcodeInfoImage = {};
      }
    },
    //条码模板选择
    handleChange(e) {
      if (arrBarcodePrintingList2.length == 0) return;
      if (!this.dialogfrom.barcodePrintTemp) return;

      let obj = arrBarcodePrintingList2.find((ite) => {
        return e == ite.templateName;
      });
      this.loading = true;
      printTemplateInfo(obj.id)
        .then((res) => {
          this.time = new Date().getTime();
          this.barcodeInfo = { ...this.barcodeInfo, ...res.data.result };
        })
        .finally((res) => {
          this.loading = false;
        });
    },
    //点击生码按钮

    clearDialog() {
      this.visible = false;
      this.$emit("refreshList");
      this.capacityTableForm = [];
    },

    handleShow() {
      if (!this.createData.barcodePrintTemp) {
        this.$message.warning(
          this.$i18n.t("mesCapacityCodePrinting.barcodePrintTempCheckMsg")
        );
        return;
      }

      this.$emit("preview", this.createData, this.capacityTableForm);
    },
  },
};
</script>
<style lang="scss" scoped>
.dialog-footer {
  padding: 20px;
  display: flex;
  justify-content: end;
}
</style>
